package middleware

import (
	"net/http"
	"voice_chat_room/pkg/jwt"

	"github.com/gin-gonic/gin"
)

// JWT中间件
func JWTAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "No token provided"})
			c.Abort()
			return
		}
		// 移除 "Bearer " 前缀
		if len(authHeader) > 7 && authHeader[:7] == "Bearer " {
			authHeader = authHeader[7:]
		}
		claims, err := jwt.ParseToken(authHeader)
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
			c.Abort()
			return
		}

		// 将用户信息保存到上下文中
		c.Set("user", claims.User)
		c.Next()
	}
}
